/*
 * @Author: Wangjun
 * @Date: 2022-05-16 16:19:21
 * @LastEditTime: 2022-06-21 14:34:43
 * @LastEditors: Wangjun
 * @Description:单文件日志
 * @FilePath: \oneareaprod:\go\src\gitee.com\haodreams\libs\flog\flog.go
 * hnxr
 */

package flog

import (
	"fmt"
	"io"
	"log"
	"os"
)

var multi = new(multiWriter)
var std = log.New(multi, "", log.LstdFlags|log.Lmicroseconds)

type multiWriter struct {
	writers []io.Writer
}

func (m *multiWriter) Write(p []byte) (n int, err error) {
	for _, w := range m.writers {
		n, err = w.Write(p)
	}
	return
}

func init() {
	multi.writers = make([]io.Writer, 0, 2)
}

func Setup(path string) (err error) {
	f, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		return
	}
	multi.writers = append(multi.writers, f)
	return
}

/**
 * @description: 关闭
 * @param {*}
 * @return {*}
 */
func Close() {
	for _, w := range multi.writers {
		if f, ok := w.(*os.File); ok && f != nil {
			f.Close()
		}
	}
}

// SetOutput sets the output destination for the standard logger.
func SetOutput(w io.Writer) {
	std.SetOutput(w)
}

// Flags returns the output flags for the standard logger.
// The flag bits are Ldate, Ltime, and so on.
func Flags() int {
	return std.Flags()
}

// SetFlags sets the output flags for the standard logger.
// The flag bits are Ldate, Ltime, and so on.
func SetFlags(flag int) {
	std.SetFlags(flag)
}

// Prefix returns the output prefix for the standard logger.
func Prefix() string {
	return std.Prefix()
}

// SetPrefix sets the output prefix for the standard logger.
func SetPrefix(prefix string) {
	std.SetPrefix(prefix)
}

// Writer returns the output destination for the standard logger.
func Writer() io.Writer {
	return std.Writer()
}

// These functions write to the standard logger.

// Print calls Output to print to the standard logger.
// Arguments are handled in the manner of fmt.Print.
func Print(v ...any) {
	std.Output(2, fmt.Sprint(v...))
}

// Printf calls Output to print to the standard logger.
// Arguments are handled in the manner of fmt.Printf.
func Printf(format string, v ...any) {
	std.Output(2, fmt.Sprintf(format, v...))
}

// Println calls Output to print to the standard logger.
// Arguments are handled in the manner of fmt.Println.
func Println(v ...any) {
	std.Output(2, fmt.Sprintln(v...))
}

// Output writes the output for a logging event. The string s contains
// the text to print after the prefix specified by the flags of the
// Logger. A newline is appended if the last character of s is not
// already a newline. Calldepth is the count of the number of
// frames to skip when computing the file name and line number
// if Llongfile or Lshortfile is set; a value of 1 will print the details
// for the caller of Output.
func Output(calldepth int, s string) error {
	return std.Output(calldepth+1, s) // +1 for this frame.
}
